import os
import re
import sys
import json
import time
import hashlib
import datetime
import requests
import configparser


def initView():  # 初始化程序
    getUniqueCode()  # 获取唯一标识码
    getVaccineStatus()  # 查询疫苗信息


def readyToSnapUp(date, time):  # 获取预约日期
    timeId = {
        "18:30-19:00": 201,
        "08:30-09:30": 223,
        "11:31-12:30": 195,
        "15:31-16:30": 198,
        "09:31-10:30": 224,
        "17:31-18:30": 200,
        "10:31-11:30": 194,
        "14:31-15:30": 197,
        "16:31-17:30": 199
    }
    userInfo['appointment'] = "预约时间：{date} -- {time}".format(
        date=date, time=time)
    print(userInfo)
    return '[{"id": "1", "title": "", "type": 1,"periods": [{"id": '+str(timeId[time])+', "date": "' + \
        date+'", "scope": "'+time+'"}]}]'


def getUniqueCode():  # 获取唯一标识码
    res = requests.get(
        'https://forms.ebdan.net/ls/tx57e4JG?share_level=1&from_user=30903d57-a89b-49f1-b7c9-8347c8d09e9b&from_id=4a529d88-5', timeout=3)
    userid = re.findall(r'id:(.*),', res.text)[0]
    md5str = str(re.findall(r'"uniqueCode":"(.*)"', res.text)
                 [0] + '5piT5LyB56eALeihqOWNleS6p+WTgTpodHRwczovL3d3dy5lcXhpdS5jb20vZWlwL3NjZW5lP3R5cGU9bGY=' + userid)
    userInfo['uniqueCode'] = hashlib.new(
        'md5', md5str.encode("utf8")).hexdigest()


def submitAppointmentInformation(param):  # 开始抢购
    data = {
        'eq[f_6051057329]': userInfo['name'],
        'eq[f_5390744344]':  userInfo['sex'],
        'eq[f_2205388182]':  userInfo['sfz'],
        'eq[f_323112639]':  userInfo['phone'],
        'eq[f_reservations_6596252657]':  param,
        'costTime': '17431',
        'fromDetail': '',
        'uniqueCode': userInfo['uniqueCode']
    }
    headers = {
        "Host": "form-preview-api.eqxiu.com",
        "content-length": "435",
        "accept": "*/*",
        "user-agent": "Mozilla/5.0 (Linux; Android 11; M2007J1SC Build/RKQ1.200826.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/87.0.4280.141 Mobile Safari/537.36",
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "origin": "https://forms.ebdan.net",
        "x-requested-with": "mark.via",
        "sec-fetch-site": "cross-site",
        "sec-fetch-mode": "cors",
        "sec-fetch-dest": "empty",
        "referer": "https://forms.ebdan.net/",
        "accept-encoding": "gzip, deflate",
        "accept-language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
    }
    res = requests.post(
        'https://form-preview-api.eqxiu.com/lp/r/12416629/795981904?code=tx57e4JG', timeout=3, headers=headers, data=data)

    jp = json.loads(res.text)
    if(jp['success']):
        print(jp['msg'])
        print("预约成功！！！！    "+json.dumps(userInfo, sort_keys=True,
                                        indent=4, ensure_ascii=False, separators=(',', ':')))
        sys.exit()
    else:
        print(jp['msg'])


def getVaccineStatus():  # 查询有没有疫苗 如果有则抢购
    res = requests.get(
        'https://form-preview-api.eqxiu.com/form/element/reservation/12416629?type=1&startTime={startTime}&endTime={endTime}&pageId=12416629&elementIds=6596252657'
        .format(startTime=userInfo['startTime'], endTime=userInfo['endTime']), timeout=3)
    jp = json.loads(res.text)
    if(jp['code'] == 200):
        arr = jp['obj'][0]['dataList']
        for date in arr:
            date_obj = arr[date]
            for btime in date_obj:
                # 千万别线程抢 已经删除多线程抢购
                time.sleep(0.2)
                submitAppointmentInformation(
                    readyToSnapUp(date=date, time=btime))
                print("日期：{date} 时间段：{time} 开始抢购".format(
                    date=date, time=btime))
        else:
            print('当前时间范围没有疫苗了')
    else:
        print('当前时间范围没有疫苗了')
        pass
    print("三秒后重新抢购")
    time.sleep(3)
    getVaccineStatus()


if __name__ == "__main__":  # 读取用户配置信息 并初始化
    curpath = os.path.dirname(os.path.realpath(__file__))
    cfgpath = os.path.join(curpath, "config.ini")
    conf = configparser.ConfigParser()
    conf.read(cfgpath, encoding="utf-8")
    userInfo = {
        'name': conf.get("lan666", "name"),
        'sex':  conf.get("lan666", "sex"),
        'sfz':  conf.get("lan666", "sfz"),
        'phone':  conf.get("lan666", "phone"),
        'uniqueCode': "",
        'appointment': "预约时间：null",
        "startTime": datetime.datetime.now().strftime("%Y-%m-%d"),
        "endTime": (datetime.datetime.now() + datetime.timedelta(days=6)).strftime("%Y-%m-%d")
    }

    print(" ‘西安’ 新冠疫苗抢购助手 V1.0")
    print
    print
    time.sleep(3)
    print("用户信息:    "+json.dumps(userInfo, sort_keys=True,
                                 indent=4, ensure_ascii=False, separators=(',', ':')))
    print
    time.sleep(1)
    print
    print("开始抢购！")
    print
    print
    print
    initView()
